﻿using System;
using System.Text;
using System.Runtime.InteropServices.Automation;

namespace MyBusiness.NET.UserCode
{
    /*
    // create a html email in Button_Execute
            string address = this.AddressCollection.SelectedItem.EMail;
            string subject = "test mail";
            string body = "<html><body> test 123 <br> 321 Test </bod></html>";

            if (string.IsNullOrEmpty(address)) return;

            MyBusiness.NET.UserCode.OutlookMailHelper.CreateOutlookEmail(address, subject, body);*/

    public static class OutlookMailHelper
    {
        private const int _mailItem = 0;
        private const int _formatPlain = 1;
        private const int _formatHtml = 2;

        public static void CreateOutlookEmail(string address, string subject, string body)
        {
            try
            {
                dynamic outlook = null;

                if (AutomationFactory.IsAvailable)
                {
                    try
                    {
                        outlook = AutomationFactory.GetObject("Outlook.Application");
                    }
                    catch (Exception ex) //If Outlook isn't open, then an error will be thrown
                    {

                        outlook = AutomationFactory.CreateObject("Outlook.Application");
                    }

                    if (outlook != null)
                    {
                        dynamic mail = outlook.CreateItem(_mailItem);

                        if (body.ToLower().Contains("<html"))
                        {
                            mail.BodyFormat = _formatHtml;
                            mail.HTMLBody = body;
                        }
                        else
                        {
                            mail.BodyFormat = _formatPlain;
                            mail.Body = body;
                        }

                        mail.Recipients.Add(address);
                        mail.Subject = subject;

                        mail.Save();
                        mail.Display();
                    }

                }

            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Failed to create email.", ex);
            }
        }
    }
}